import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web
import MySQLdb
import time
import readdata

RPI = None
Web = None


class WSHandler(tornado.websocket.WebSocketHandler):
    RPI_status = "Idle"
    def open(self):
        print 'new connection'
        self.write_message("CREAD")
        self.write_message("CREAD")
        self.write_message("CSTOP")

    def on_message(self, message):
        global RPI,Web
        print 'message received %s' % message
        data = message.split("&&")
        if data[0] == 'login':
            RPI = self
            RPI.write_message(read.login(data[1],data[2]))
            if(Web is not None):
                Web.write_message("HWconn")
        elif data[0] == "add": 
            result = read.addData(data[1],data[2]) 
            RPI.write_message(result)
            if(result == "Commit"):
                Web.write_message("add&&"+data[1]+"&&"+data[2])
                print "sent to web"
        elif data[0] == "del":
            read.delData(data[1])
        elif data[0] == "CREAD":
            if(self.RPI_status == "Idle"):
                self.RPI_status = "Read"
                RPI.write_message("CREAD")
                Web.write_message("status&&Reading")
                print "CREAD sent"
        elif data[0] == "CWRITE":
            if(self.RPI_status != "Idle"):
                RPI.write_message("CSTOP")
                self.RPI_status = "Idle"
            if(len(data) > 0):
                RPI.write_message(message)
                print "CWRITE sent"
        elif data[0] == "CSELL":
            RPI.write_message("CSELL")
            print "CSELL sent"
        elif data[0] == "CSTOP":
            RPI.write_message("CSTOP")
            self.RPI_status = "Idle"
            Web.write_message("status&&Idle")
            print "CSTOP sent"
        elif data[0] == "WebApp":
            if (Web is None):
                Web = self
                Web.write_message("Accept")
                print "Accept Connecttion from " + str(self)
            else: self.close()
        elif data[0] == "Webdisconn":
                Web.close()
                Web = None
        elif data[0] == "HWstatus":
            if (RPI is not None):
                self.write_message("HWconn")
            else: self.write_message("HWdisconn")
        elif data[0] == "Re":
            if(Web is not None):
                if(data[1] == "True"): Web.write_message("status&&Idle : Write Success")
                else : Web.write_message("status&&Idle : Write fail")

    def on_close(self):
        global Web,RPI
        if(Web == self):
            RPI.write_message("CSTOP")
            Web = None
        elif(RPI==self):
            if(Web is not None):
                Web.write_message("HWdisconn")
            RPI = None
            read.closedb()
        print 'connection closed'

application = tornado.web.Application([
    (r'/', WSHandler),
])

read = readdata.Inventoryread()

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(8888)
    tornado.ioloop.IOLoop.instance().start()
